package com.dgut.legalservice.vCode;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

public class FileUpLoad {

    //上传文件到img目录下

    public String fileUpload(MultipartFile uploadFile, HttpServletRequest request, HttpSession session) throws IOException {
        //photoAttId 头像路径
        String url = "../img";

        //定义⽂件名
        String fileName = "";
        //1.获取⽂件名
        String uploadFileName = uploadFile.getOriginalFilename();
        //2.截取⽂件名
        String extendName =
                uploadFileName.substring(uploadFileName.lastIndexOf(".") + 1);
        //3.把⽂件加上随机数，防⽌⽂件重复
        String uuid = UUID.randomUUID().toString().replace("-",
                "").toUpperCase();
        //4.判断是否输⼊了⽂件名
        fileName = uuid + "_" + uploadFileName;
        String basePath = "D:/LegalServiceWeb/src/main/resources/static/img";
        //3.解决同⼀⽂件夹中⽂件过多问题
        String datePath = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        //4.判断路径是否存在
        File file = new File(basePath + "/" + datePath);
        if (!file.exists()) {
            file.mkdirs();
        }
        //url格式../img/2019-12-19/fileName
        url = url+"/"+datePath+"/"+fileName;
        session.setAttribute("photoAttId",url);  //更新session的头像photoAttId路径
        uploadFile.transferTo(new File(file, fileName));
        return url;
    }


}
